<?php

namespace App\Http\Controllers\Api;

use App\Analysis;
use App\Analysitical;
use App\Assessment;
use App\SubjectPower;
use App\SubjectSort;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;

/**
 * Class AssessmentController
 * @package App\Http\Controllers\Api
 * 心理学评估
 */
class AssessmentController extends BaseController
{
    /**
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request)
    {
        $orderBy = $request->order_by ? $request->order_by : 'id';
        $orderType = $request->order_type ? $request->order_type : 'desc';
        $pageSize = $request->page_size ? $request->page_size : $this->pageSize;
        $lists = Assessment::orderBy($orderBy, $orderType)->with(['user'])->paginate($pageSize);
        return $lists;
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * @param Assessment $assessment
     * @return Assessment
     */
    public function show(Assessment $assessment)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Assessment $assessment
     * @return \Illuminate\Http\Response
     */
    public function edit(Assessment $assessment)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \App\Assessment $assessment
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Assessment $assessment)
    {
        $assessment->update($request->only(['assessment']));//只可以修改做题结果
        return response(['message' => '修改成功']);
    }

    /**
     * @param Assessment $assessment
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     * @throws \Exception
     */
    public function destroy(Assessment $assessment)
    {
        $assessment->delete();
        return response(['message' => '删除成功']);
    }

    /**
     * @param Request $request
     * @param Assessment $assessment
     * @param $sort
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     * 评估提交
     */
    public function pinggu(Request $request, Assessment $assessment, $sort)
    {
        $user_id = Auth::id();
        $data = $request->all();
        $SubjectPower = SubjectPower::where('user_id', $user_id)->where('status', 0)->where('subject_sort_id', $sort)->first();
        $sorts = SubjectSort::find($sort);
        if (!$sorts) {
            return response(['message' => '评估失败，请检查', 'code' => 0], 400);
        }
//        if ($sorts->price >= 0 && !$SubjectPower) {
//            return response(['message' => '请先购买', 'code' => 2], 400);
//        }

        if (!$data) {
            return response(['message' => '请提交评估结果', 'code' => 0], 400);
        }
        //同时一样多的情况想让谁在前前面就调此数组的顺序 比如C 和A一样多C 在前面就默认答案时C
        $criterion = [
            'A' => 0,
            'B' => 0,
            'C' => 0,
            'D' => 0,
            'E' => 0,
            'F' => 0,
            'G' => 0,
            'H' => 0,
            'I' => 0,
            'W' => 0,
            'N' => 0,
            'G' => 0,
            'Z' => 0,
            'S' => 0,
            'Q' => 0,
            'P' => 0,
            'R' => 0,
        ];
        foreach ($data as $v) {
            foreach ($criterion as $key => $value) {
                if ($v == $key) {
                    $criterion[$key] += 1;
                }
            }
        }
        if ($sort == 1) {//简单评估
            $j1 = 'N';
            $j2 = 'Z';
            $j3 = 'Q';
            $j4 = 'R';
            if ($criterion['W'] > $criterion['N']) {
                $j1 = 'W';
            }
            if ($criterion['G'] > $criterion['Z']) {
                $j1 = 'G';
            }
            if ($criterion['S'] > $criterion['Q']) {
                $j1 = 'S';
            }
            if ($criterion['P'] > $criterion['R']) {
                $j1 = 'P';
            }
            $assessment = $j1 . $j2 . $j3 . $j4;
        } elseif ($sort == 2) {//完整评估
            $wz = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'];
            $newArray = $criterion;
            foreach ($criterion as $k => $v) {
                foreach ($newArray as $key => $value) {
                    if (!in_array($k, $wz)) {
                        unset($criterion[$k]);
                    }
                    if ($v < $value) {
                        unset($criterion[$k]);
                    }
                }
            }
            $keyarray = array_keys($criterion);
            $assessment = $keyarray[0];//取第一个结果
            if (!in_array($assessment, $wz)) {
                return response(['message' => '评估失败', 'code' => 0], 400);
            }
        } else {
            return response(['message' => '未开发的评估方式', 'code' => 0], 400);
        }
        $res = Assessment::create(['user_id' => $user_id, 'assessment' => $assessment, 'subject_sort_id' => $sort]);
        if ($res) {
            //减去这次评估机会
            if ($SubjectPower) {
                $SubjectPower->status = 1;
                $SubjectPower->save();
            }
            return response(['message' => '评估成功', 'code' => 1]);
        }
        return response(['message' => '系统繁忙', 'code' => 0], 500);
    }

    /**
     * @param Request $request
     * @param Assessment $assessment
     * 获取用户最新评估结果
     * assessments_id  获取指定评估结果
     */
    public function GetAssessment(Request $request, Assessment $assessment, $user_id)
    {
        $new = $assessment->orderBy('id', 'desc')->where('user_id', $user_id);
        if ($request->subject_sort_id) {
            $new = $new->where('subject_sort_id', $request->subject_sort_id);
        }
        if ($request->assessments_id) {
            $new = $new->where('id', $request->assessments_id);
        }
        $new = $new->first();
        if (!$new) {
            return response(['message' => '暂无评估结果', 'data' => []]);
        }
        $anArray = str_split($new->assessment, 1);
        $len = count($anArray);
        $assessment = $this->combine($anArray, $len);
        $assessments = [];
        foreach ($assessment as $v) {
            $assessments[] = implode('', $v);
        }
        $analysis = Analysitical::where('subject_sort_id', $new->subject_sort_id)->whereIn('answer', $assessments)->value('analysis');
        $new->analysis = $analysis;
        return response(['message' => '获取成功', 'data' => $new]);
    }

    /**
     * @param Request $request
     * @param Assessment $assessment
     * @param $user_id
     * @return mixed
     * 评估历史记录
     */
    public function history(Request $request, Assessment $assessment, $user_id)
    {
        $list = $assessment->orderBy('id', 'desc')->where('user_id', $user_id)->with(['sort']);
        if ($request->subject_sort_id) {
            $list = $list->where('subject_sort_id', $request->subject_sort_id);
        }
        $list = $list->get();
        return $list;
    }

}
